package magent

import (
	"database/sql"
	"log"

	"fmt"

	_ "github.com/mattn/go-sqlite3"
	"github.com/spf13/viper"
)

var sqlite *sql.DB

func initSqlite(uri string) *sql.DB {
	db, err := sql.Open("sqlite3", uri)
	if err != nil {
		log.Panic(err)
	}
	return db
}

func pingDB() {
	if err := sqlite.Ping(); err != nil {
		log.Panic(err)
	}
}

// CreateTable to create sqlite last table.
func CreateTable(configPath string) {
	err := initConfig(configPath)
	if err != nil {
		log.Panic(err)
	}
	db := initSqlite(viper.GetString("SqliteURI"))
	_, err = db.Exec(`DROP TABLE IF EXISTS last; CREATE TABLE "last" (
"id"  INTEGER NOT NULL,
"value"  TEXT,
"type"  TEXT NOT NULL,
PRIMARY KEY ("id" ASC)
);`)
	if err != nil {
		log.Panic(err)
	}

	_, err = db.Exec(`DROP TABLE IF EXISTS servers; CREATE TABLE "servers" (
"id"  INTEGER NOT NULL,
"host"  TEXT NOT NULL,
"name" TEXT NOT NULL,
PRIMARY KEY ("id")
);`)
	if err != nil {
		log.Panic(err)
	}

	_, err = db.Exec(
		"INSERT INTO last (value, type) VALUES ($1, $2), ($3, $4), ($5, $6)",
		"2016-11-20 12:00", "oplog", "2016-11-20 12:00", "offline_todo",
		"2016-11-20 12:00", "error_log")
	if err != nil {
		log.Panic(err)
	}

	_, err = db.Exec(
		"INSERT INTO servers (host, name) VALUES ($1, $2), ($3, $4), ($5, $6)",
		"localhost:9999", "plm", "localhost:10002", "file", "localhost:10003", "cms")
	if err != nil {
		log.Panic(err)
	}
}

func getLast(typ string) (string, error) {
	var last string
	row := sqlite.QueryRow("SELECT value FROM last WHERE type = $1", typ)
	err := row.Scan(&last)
	if err != nil {
		return "", fmt.Errorf("Cannot get last of %s from db.\v%s", typ, err)
	}
	return last, nil
}

func updateLast(typ, last string) error {
	_, err := sqlite.Exec("UPDATE last SET value=$1 WHERE type=$2", last, typ)
	if err != nil {
		return fmt.Errorf("Cannot update last of %s to db.\n%v", typ, err)
	}
	return nil
}

func getServers() ([]Server, error) {
	rows, err := sqlite.Query("SELECT host, name FROM servers")
	if err != nil {
		return nil, fmt.Errorf("Cannot get servers from db.\v%s", err)
	}
	servers := make([]Server, 0)
	for rows.Next() {
		var server Server
		if err := rows.Scan(&server.host, &server.name); err != nil {
			return nil, fmt.Errorf("Cannot get servers from db.\v%s", err)
		}
		servers = append(servers, server)
	}
	return servers, nil
}
